package com.hmall.search.service.init;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import com.hmall.search.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.WeightBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {
    private Map<String,List<String>> map = new HashMap<>();
    private List<String> brand = new ArrayList<>();
    private List<String> category = new ArrayList<>();

    @Autowired
    RestHighLevelClient client;

    @Override
    public List<String> getSuggest(String key) throws IOException {
        SearchRequest request = new SearchRequest("item");
        request.source().suggest(new SuggestBuilder().addSuggestion("mysuggest", SuggestBuilders
                .completionSuggestion("suggestion")
                .prefix(key)
                .skipDuplicates(true)
                .size(10)));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        CompletionSuggestion suggestion = response.getSuggest().getSuggestion("mysuggest");
        ArrayList<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option options : suggestion.getOptions()) {
            String suggestText = options.getText().string();
            log.warn("提示为   {}  ",suggestText);
            list.add(suggestText);
        }
        return list;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams param) throws IOException {
        map.clear();
        category.clear();
        brand.clear();
        category = getCategory(param);
        brand = getBrand(param);
        log.warn("分类为{}",category);
        log.warn("品牌为{}",brand);
        map.put("category",category);
        map.put("brand",brand);
        return map;
    }

    @Override
    public PageDTO<ItemDoc> getList(RequestParams param) throws IOException {
        String key = param.getKey();
        String brand = param.getBrand();
        String sortBy = param.getSortBy();
        Integer maxPrice = param.getMaxPrice();
        Integer minPrice = param.getMinPrice();
        Integer page = param.getPage();
        Integer size = param.getSize();
        SearchRequest request = new SearchRequest("item");
        BoolQueryBuilder builder = new BoolQueryBuilder();
        if (key == null || "".equals(key)){
            builder.must(QueryBuilders.matchAllQuery());
        }else {
            builder.must(QueryBuilders.matchQuery("all",key));
        }
        if (brand != null && !"".equals(brand)){
            builder.filter(QueryBuilders.termQuery("brand",brand));

        }
        if (maxPrice != null){
            builder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }
        if (minPrice != null){
            builder.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        //排序
        if ("price".equals(sortBy)){
            request.source().sort("price", SortOrder.DESC);
        }else if ("sold".equals(sortBy)){
            request.source().sort("sold",SortOrder.DESC);
        }
        //分页
        request.source().from((page - 1)* size).size(size);
        //高亮
        request.source().highlighter(new HighlightBuilder().preTags("<em>").postTags("</em>").field("name").requireFieldMatch(false));
        //算分排名
        WeightBuilder weightBuilder = ScoreFunctionBuilders.weightFactorFunction(10);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builder,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("isAD",true),weightBuilder)
        });
        request.source().query(functionScoreQueryBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        PageDTO<ItemDoc> pageDTO = ResponseUtil.respHandler(response);
        return pageDTO;
    }

    @Override
    public void addDoc(String jsonStr) throws IOException {
        ItemDoc itemDoc = JSON.parseObject(jsonStr, ItemDoc.class);
        IndexRequest request = new IndexRequest("item").id(String.valueOf(itemDoc.getId()));
        request.source(jsonStr, XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    @Override
    public void deleteDoc(String id) throws IOException {
        DeleteRequest request = new DeleteRequest("item").id(id);
        client.delete(request,RequestOptions.DEFAULT);
    }

    private List<String> getCategory(RequestParams param) throws IOException {
        String key = param.getKey();
        SearchRequest request = new SearchRequest("item");
        if (key == null|| "".equals(key)){
            request.source().query(QueryBuilders.matchAllQuery()).size(0);
        }else {
            request.source().query(QueryBuilders.matchQuery("all",key)).size(0);
        }
        request.source().aggregation(AggregationBuilders.terms("category").field("category").size(20));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("category");
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            category.add(bucket.getKeyAsString());
        }
        return category;
    }

    private List<String> getBrand(RequestParams param) throws IOException {
        String key = param.getKey();
        SearchRequest request = new SearchRequest("item");
        if (key == null|| "".equals(key)){
            request.source().query(QueryBuilders.matchAllQuery()).size(0);
        }else {
            request.source().query(QueryBuilders.matchQuery("all",key)).size(0);
        }
        request.source().aggregation(AggregationBuilders.terms("brand").field("brand").size(20));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("brand");
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            brand.add(bucket.getKeyAsString());
        }
        return brand;
    }


}
